package com.example.commons.id;

import com.example.commons.time.TimeTools;
import org.apache.commons.lang3.StringUtils;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

public class Serial {
    private static final String USER_ID = "12345678998123";
    private static final AtomicInteger counter = new AtomicInteger(0);
/*    public static void main(String[] args) {
        generateOrderNumbersConcurrently();
    }*/
    //测试1
    public static void generateOrderNumbersConcurrently() {
        int threadCount = 10;
        int requestCountPerThread = 1000;

        for (int i = 0; i < threadCount; i++) {
            Thread thread = new Thread(() -> {
                for (int j = 0; j < requestCountPerThread; j++) {
                    String orderNumber = getOrderId(USER_ID);
                    System.out.println(Thread.currentThread().getName() + ": " + orderNumber);
                }
            });
            thread.start();
        }
    }

    /**
     * 方式1 ： 当前日期+用户ID+随机数
     * @param userId
     * @return
     */
    public static String getOrderId(String userId) {
        StringBuilder sb = new StringBuilder();
        // 添加当前日期
        sb.append(TimeTools.getTime());
        // 添加用户ID
        sb.append(userId);
        // 添加自增计数器
        int count = counter.incrementAndGet();
        sb.append(String.format("%04d", count % 10000));
        return sb.toString();
    }


    public static String getTimeStartOrdId() {
        return StringUtils.join(TimeTools.getMillisecTime(), getHashCode(1));
    }
    /**
     * 百万级连续生成约0.02%的重复率
     *
     * @param prefix
     * @return
     */
    public static String getHashCode(int prefix) {
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if (hashCodeV < 0) {
            hashCodeV = -hashCodeV;
        }
        return prefix + String.format("%010d", hashCodeV);
    }
}
